/*
 * WorkUnitMonitor.cpp
 *
 *  Created on: Jul 3, 2009
 *      Author: rpledge
 */
#include <iostream>
#include "WorkUnitMonitor.h"
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sstream>
#include <arpa/inet.h>


namespace ComputingObjects {

WorkUnitMonitor::WorkUnitMonitor(std::string monitorAddress, int port)
 : myMonitorAddress(monitorAddress), myPort(port)
{
	struct sockaddr_in sock;
	sock.sin_family = AF_INET;
	sock.sin_port = htons(myPort);
	inet_pton(AF_INET, myMonitorAddress.c_str(), &sock.sin_addr);

	mySocket = socket(AF_INET, SOCK_DGRAM, 0);
	if (mySocket == -1) {
		std::cout<<"Create socket failed"<<std::endl;
	}
	if (connect(mySocket, (sockaddr*) &sock, sizeof(sock))) {
		perror("connect");
	}
}

WorkUnitMonitor::~WorkUnitMonitor() {
	// TODO Auto-generated destructor stub
}

void WorkUnitMonitor::stateChange(WorkUnit& unit, enum WorkUnit::state previousState)
{
	// Send the state change notification to the monitor address
	std::stringstream message;
	message<<"Unit: "<<unit.getID()<<" state: "<<WorkUnit::stateString(unit.getState())<<std::endl;
	std::string data(message.str());
	if (send(mySocket, data.c_str(), data.size(), 0) < 0) {
		std::cout<<"send failed"<<std::endl;
	}
}


}
